package servlets;

import java.io.IOException;
import java.util.Hashtable;

import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import student.Student;
import student.StudentHome;
import user.User;
import user.UserHome;
import academicSupSession.AcademicSupSession;

import company.CompanyHome;
import compsup.CompanySup;
import compsup.CompanySupHome;

import degree.Degree;
import degree.DegreeHome;
import descriptor.CompaniesListDescriptor;
import descriptor.DegreeDescriptor;
import descriptor.FeedbackDescriptor;
import descriptor.FeedbackListDescriptor;
import descriptor.PlacementDiaryDescriptor;
import descriptor.QueryDescriptor;
import descriptor.QueryListDescriptor;
import descriptor.StudentDescriptor;
import descriptor.StudentListDescriptor;
import descriptor.UsersListDescriptor;
import extras.Md5Encryption;
import feedback.Feedback;
import feedback.FeedbackHome;

public class AcademicSupServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
	throws IOException, ServletException
	{
		doPostAndGet(req,res);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse res)
	throws IOException, ServletException
	{
		doPostAndGet(req,res);
	}

	protected void doPostAndGet(HttpServletRequest req ,HttpServletResponse res)
	throws IOException, ServletException
	{
		Context initialContext = null;
		try {
			initialContext = new InitialContext() ;
		} catch (NamingException e) {
			e.printStackTrace();
		}
		HttpSession session = req.getSession(true);
		AcademicSupSession academicSup = (AcademicSupSession)session.getAttribute("academicSup");
		String page = req.getParameter("page") ;
		RequestDispatcher dispatcher = null ;
		if(academicSup == null){
			dispatcher = req.getRequestDispatcher("index.jsp") ;
			dispatcher.forward(req, res) ;
			return;
		}

		req.setAttribute("academicSup", academicSup.getDescriptor());
		req.setAttribute("userSurname",academicSup.getSurname());
		req.setAttribute("userFirstname", academicSup.getFirstname());

		if(page.equalsIgnoreCase("index")){
			session.removeAttribute("academicSup");
			dispatcher = req.getRequestDispatcher("index.jsp");
		}if(page.equalsIgnoreCase("academicSupervisorView")){
			req.setAttribute("listStudents", academicSup.getStudents());
			dispatcher = req.getRequestDispatcher("academicSupervisor/"+page+".jsp");
		}if(page.equalsIgnoreCase("academicSupervisorQueriesView")){
			QueryListDescriptor listQuery = academicSup.getQueries();
			StudentListDescriptor studentList = new StudentListDescriptor(); 
			for(QueryDescriptor query : listQuery.getQueryList()){
				StudentDescriptor student = getStudent(query.getStudentID()).getDescriptor();
				studentList.addStudent(student);
			}
			req.setAttribute("listStudent", studentList);
			req.setAttribute("listQueries", listQuery);
			dispatcher = req.getRequestDispatcher("academicSupervisor/"+page+".jsp");
		}if(page.equalsIgnoreCase("academicSupervisorViewDegree")){
			req.setAttribute("listDegrees", academicSup.getDegrees());
			dispatcher = req.getRequestDispatcher("academicSupervisor/"+page+".jsp");
		}if(page.equalsIgnoreCase("academicSupervisorViewDegreeFeedback")){

			int degreeId = Integer.parseInt(req.getParameter("degreeId"));
			Object objref;
			Object objrefUser;
			Object objrefCompany;
			Object objrefCompanySup;
			DegreeDescriptor desc = null;
			FeedbackListDescriptor feedDesc = null;
			UsersListDescriptor userDesc = new UsersListDescriptor();
			CompaniesListDescriptor compDesc = new CompaniesListDescriptor();
			Hashtable<Integer, Integer> userToCompany = new Hashtable<Integer, Integer>();
			try {
				objref = initialContext.lookup("MyDegree_L");

				DegreeHome DegreeHome = (DegreeHome)PortableRemoteObject.narrow(objref, DegreeHome.class) ;
				Degree degree = DegreeHome.findByPrimaryKey(degreeId);
				desc = degree.getDescriptor();
				objrefUser = initialContext.lookup("MyUser_L");
				UserHome userhome = (UserHome)PortableRemoteObject.narrow(objrefUser, UserHome.class);
				objrefCompany = initialContext.lookup("MyCompany_L");
				CompanyHome companyHome = (CompanyHome)PortableRemoteObject.narrow(objrefCompany, CompanyHome.class);
				objrefCompanySup = initialContext.lookup("MyCompanySup_L");
				CompanySupHome companysupHome = (CompanySupHome)PortableRemoteObject.narrow(objrefCompanySup, CompanySupHome.class);
				feedDesc = degree.getFeebackDescriptors();
				for(FeedbackDescriptor fTempDesc: feedDesc.getFeedbackDescriptors()){
					User user = userhome.findByPrimaryKey(fTempDesc.getAuthorId());
					userDesc.addUserDescriptor(user.getDescriptor());
					if (user.getType() == 8){
						CompanySup companySup  = companysupHome.findByPrimaryKey(user.getId());
						compDesc.addCompanyDescriptor(companySup.getCompany().getDescriptor());
						userToCompany.put(user.getId(), companySup.getCompany().getId());
					}
				}
			} catch (NamingException e) {
				e.printStackTrace();
			} catch (FinderException e) {
				e.printStackTrace();
			}

			req.setAttribute("degree", desc);
			req.setAttribute("feedbackList", feedDesc);
			req.setAttribute("userList", userDesc);
			req.setAttribute("userToCompany", userToCompany);
			req.setAttribute("companyList", compDesc);
			dispatcher = req.getRequestDispatcher("academicSupervisor/"+page+".jsp");
		}if(page.equalsIgnoreCase("academicSupervisorQueryAccepted")){
			int queryId = Integer.parseInt(req.getParameter("queryId"));
			academicSup.acceptQuery(queryId);
			dispatcher = req.getRequestDispatcher("academicSupervisor/"+page+".jsp");
		}if(page.equalsIgnoreCase("academicSupervisorQueryRejected")){
			int queryId = Integer.parseInt(req.getParameter("queryId"));
			academicSup.rejectQuery(queryId);
			dispatcher = req.getRequestDispatcher("academicSupervisor/"+page+".jsp");
		}if(page.equalsIgnoreCase("academicSupervisorViewFeedback")){
			int studentId = Integer.parseInt(req.getParameter("userId"));
			Student student = null;
			try {
				StudentHome studentHome = (StudentHome)initialContext.lookup("MyStudent_L");
				student = studentHome.findByPrimaryKey(studentId);
			} catch (FinderException e) {
				e.printStackTrace();
			} catch (NamingException e) {
				e.printStackTrace();
			}
			FeedbackDescriptor desc = student.getAcademicSupFeedback().getDescriptor();
			req.setAttribute("feedback", desc);
			req.setAttribute("degree", student.getDegree().getDescriptor());
			req.setAttribute("student", student.getDescriptor());
			dispatcher = req.getRequestDispatcher("academicSupervisor/"+page+".jsp");
		}if(page.equalsIgnoreCase("academicSupervisorViewStudentDiary")){
			int studentId = Integer.parseInt(req.getParameter("userId"));
			Student student = null;
			try {
				StudentHome studentHome = (StudentHome)initialContext.lookup("MyStudent_L");
				student = studentHome.findByPrimaryKey(studentId);
			} catch (FinderException e) {
				e.printStackTrace();
			} catch (NamingException e) {
				e.printStackTrace();
			}
			PlacementDiaryDescriptor desc = student.getPlacementDiary().getDescriptor();
			req.setAttribute("diary", desc);
			req.setAttribute("degree", student.getDegree().getDescriptor());
			req.setAttribute("student", student.getDescriptor());
			dispatcher = req.getRequestDispatcher("academicSupervisor/"+page+".jsp");
		}
		if(page.equalsIgnoreCase("academicSupervisorSettings")){
			req.setAttribute("result", "");
			dispatcher = req.getRequestDispatcher("academicSupervisor/academicSupervisorSettings.jsp");
		}else if(page.equalsIgnoreCase("academicSupervisorEditReport")){
			int studentId = Integer.parseInt(req.getParameter("userId"));
			Student student = getStudent(studentId);
			Feedback feedback = student.getAcademicSupFeedback();
			if (feedback == null){
				Feedback newFeedback=null;
				try{
					FeedbackHome feedbackHome = (FeedbackHome)initialContext.lookup("MyFeedback_L");
					UserHome userHome = (UserHome)initialContext.lookup("MyUser_L");
					User academicSupUser = userHome.findByPrimaryKey(academicSup.getId());
					newFeedback = feedbackHome.create("Report on "+student.getFirstName()+" "+student.getName(), "Enter your report Here", academicSupUser);
				}catch (NamingException ex) {
					ex.printStackTrace();
				}
				catch (FinderException e) {
					e.printStackTrace();
				} catch (CreateException e) {
					e.printStackTrace();
				}
				student.setAcademicSupFeedback(newFeedback);
			}
			req.setAttribute("feedback", student.getAcademicSupFeedback().getDescriptor());
			req.setAttribute("student", student.getDescriptor());
			dispatcher = req.getRequestDispatcher("academicSupervisor/"+page+".jsp");
		}
		else if(page.equalsIgnoreCase("academicSupervisorEditReportDone")){
			String feedbackContent = req.getParameter("feedback");
			int studentId = Integer.parseInt(req.getParameter("userId"));
			Student student = getStudent(studentId);
			student.getAcademicSupFeedback().setInfos(feedbackContent);
			req.setAttribute("listStudents", academicSup.getStudents());
			dispatcher = req.getRequestDispatcher("academicSupervisor/academicSupervisorView.jsp");
		}
		else if(page.equalsIgnoreCase("setSettings")){
			String firstName = req.getParameter("firstName") ;
			String surName = req.getParameter("surName") ;
			String passwd = req.getParameter("passwd1") ;
			String passwd2 = req.getParameter("passwd2") ;
			String email = req.getParameter("email") ;
			String result = "Changement done!";
			if(!passwd.equals("") || !passwd2.equals("")){
				//change the passwd;
				if(passwd.equals(passwd2)){
					academicSup.setPassword(Md5Encryption.getEncodedPassword(passwd));
					academicSup.setFirstname(firstName);
					academicSup.setSurname(surName);
					academicSup.setEmail(email);
				}else{
					result = "password don't match";
				}
			}
			academicSup.setFirstname(firstName);
			academicSup.setSurname(surName);
			academicSup.setEmail(email);
			req.setAttribute("result", result);
			dispatcher = req.getRequestDispatcher("academicSupervisor/academicSupervisorSettings.jsp");
		}
		if (dispatcher != null) dispatcher.forward(req, res) ;
	}


	public Student getStudent (int studentId){
		Student student = null;
		InitialContext initialContext =null;
		try {
			initialContext =  new InitialContext();
			StudentHome studentHome = (StudentHome)initialContext.lookup("MyStudent_L");
			student = studentHome.findByPrimaryKey(studentId);
		} catch (FinderException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return student;
	}
}
